<template>
  <div>
    <div class="titFirst">
      <div><i class="iconfont icon-shixinyuan"></i>农具类型管理</div>
      <div
        style="display:flex;justify-content: space-around;align-items: center;"
      >
        <el-button type="primary" @click="newList">新&nbsp;&nbsp;增</el-button>
        <el-button :disabled="!enableDel" type="danger" @click="remove">删&nbsp;&nbsp;除</el-button>
<!--        <div class="btn_purpose_left" @click="newList">新增</div>-->
<!--        <div class="btn_purpose_right" @click="remove">删除</div>-->
      </div>
    </div>
    <div>
      <div class="block">
        <el-tree
          :data="dataList"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="defaultProps"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
          @check-change="danxuan"
          ref="tree"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                type="text"
                size="mini"
                @click="append(data)"
                style="margin-right:20px"
              >
                <i class="iconfont icon-chilun"></i>
              </el-button>
              <!-- <el-button
                type="text"
                size="mini"
                @click="() => remove(node, data)"
              >
                Delete
              </el-button> -->
            </span>
          </span>
        </el-tree>
        <!--修改信息--->
        <el-dialog title="修改农具" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false">
          <el-form ref="toolFormData" :model="fromData" label-width="80px" :rules="toolDataRules" style="padding-right: 20px">
            <el-form-item label="农具" prop="goodName"
              ><el-input
                v-model="fromData.goodName"
                placeholder="农具名称"
              ></el-input
            ></el-form-item>
            <el-form-item label="序号" prop="orderNum"
              >
              <el-input-number v-model="fromData.orderNum" :min="1" :max="1000" label="序号"
                               style="width: 100%"></el-input-number>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <div style="display: flex;justify-content: flex-end;padding-right: 20px;margin-top: -36px">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="sendInfo">确 定</el-button>
            </div>
          </span>
        </el-dialog>
        <!----新增------>
        <el-dialog title="新增农具" :visible.sync="addNews" width="40%"
                   :close-on-click-modal="false">

          <div class="block">
            <el-form ref="toolForm" label-width="80px" :model="from" :rules="toolRules" style="padding-right: 20px">
              <el-form-item label="父级" prop="parentId">
                <el-cascader
                  style="width: 100%"
                  :options="seleList"
                  :props="{
                    checkStrictly: true,
                    value: 'id',
                    label: 'goodName',
                    children: 'children',
                    expandTrigger: 'hover'
                  }"
                  clearable
                  ref="cascaderAddr"
                  @change="newSelet"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="农具" prop="goodName">
                <el-input
                  v-model.trim="from.goodName"
                  placeholder="农具名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="序号" prop="orderNum">
                <el-input-number v-model="from.orderNum" :min="1" :max="1000" label="序号"
                                 style="width: 100%"></el-input-number>
              </el-form-item>
            </el-form>

            <span slot="footer">
              <div style="display: flex;justify-content: flex-end;padding-right: 20px;margin-top: 30px">
                <el-button @click="addNews = false">取 消</el-button>
                <el-button type="primary" @click="delivery">确 定</el-button>
              </div>
            </span>
          </div>

<!--          <div class="block">-->
<!--            <el-form ref="form" label-width="80px" v-model="from">-->
<!--              <el-form-item label="添加菜单">-->
<!--                <el-cascader-->
<!--                  :options="seleList"-->
<!--                  :props="{-->
<!--                    checkStrictly: true,-->
<!--                    value: 'id',-->
<!--                    label: 'goodName',-->
<!--                    children: 'children'-->
<!--                  }"-->
<!--                  clearable-->
<!--                  ref="cascaderAddr"-->
<!--                  @change="newSelet"-->
<!--                ></el-cascader>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="新增信息">-->
<!--                <el-input-->
<!--                  v-model="from.goodName"-->
<!--                  placeholder="请输入新增信息"-->
<!--                ></el-input>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="序号">-->
<!--                <el-input-->
<!--                  v-model="from.orderNum"-->
<!--                  placeholder="请输入序号"-->
<!--                ></el-input>-->
<!--              </el-form-item>-->
<!--            </el-form>-->

<!--            <span slot="footer" class="dialog-footer">-->
<!--              <el-button @click="addNews = false">取 消</el-button>-->
<!--              <el-button type="primary" @click="delivery">确 定</el-button>-->
<!--            </span>-->
<!--          </div>-->
        </el-dialog>
        <!--删除--->
<!--        <el-dialog title="是否删除" :visible.sync="delet">-->
<!--          <div v-for="(item, index) in deleArry" :key="index">-->
<!--            <div>{{ item.label }}</div>-->
<!--          </div>-->
<!--          <el-button type="primary" @click="deleClick">确认删除</el-button>-->
<!--        </el-dialog>-->
      </div>
    </div>
  </div>
</template>

<script>
// let id = 1000;
import "@/icon/iconfont.css";
import PubSub from "pubsub-js";
import {
  newaddMaterial,
  typelistMaterial,
  checkmaterialList,
  reviseMaterial,
  deleteMaterial,
  checkMaterial
} from "@/api/material";
export default {
  props: ["name"],
  created() {
    // this.queryList();
  },
  data() {
    const validateEditName = (rule, value, callback) => {
        if (this.fromData.goodName==null || this.fromData.goodName==undefined || this.fromData.goodName === '') {
            callback(new Error('请输入农资名称'));
        } else {
            callback();
        }
    };
    const validateName = (rule, value, callback) => {
        if (this.from.goodName==null || this.from.goodName==undefined || this.from.goodName === '') {
            callback(new Error('请输入农资名称'));
        } else {
            callback();
        }
    };
    const validateParent = (rule, value, callback) => {
        if (this.from.parentId != null || this.from.parentId=='') {
            callback();
        } else {
            callback(new Error('请选择父级'));
        }
    };
    return {
      typeOfnj: 0,
      wzParentId: "",
      wzId: "",
      list: [],
      fromData: {
          goodName:"",
          orderNum:""
      },
      lastArr: [],
      enableDel: false,
      childArr: [],
      dataList: [],
      from: {},
      seleList: [],
      sortMenu: "",
      delet: false,
      saveId: [],
      deleArry: [],
      xzInput: "",
      addNews: false,
      targetNode: null,
      // info: "",
      dialogVisible: false,
      defaultProps: {
        children: "children",
        label: "goodName"
      },
        toolDataRules: {
            goodName: [{
                validator: validateEditName, trigger: 'blur',
                required: true
            }],
        },
        toolRules: {
            goodName: [{
                validator: validateName, trigger: 'blur',
                required: true
            }],
            parentId: [{
                validator: validateParent, trigger: 'change',
                required: true
            }]
        }
      // data: JSON.parse(JSON.stringify(data))
      // title:""
    };
  },
    watch: {
        lastArr: {
            handler(n, o) {
                this.enableDel = n && n.length > 0
            },
            immediate: true
        },
        dialogVisible:{
            handler(n,o){
                if(!n){
                    this.$nextTick(()=>{
                        Object.assign(this.$data.fromData, this.$options.data.fromData);
                        this.$refs.toolFormData.resetFields();
                    })
                }
            }
        },
        addNews: {
            handler(n,o){
                if(!n){
                    this.$nextTick(()=>{
                        Object.assign(this.$data.from, this.$options.data.from);
                        this.$refs.toolForm.resetFields();
                    })
                }
            }
        }
    },
  methods: {
    deleClick() {
      this.delet = false;
      const loading = this.$load(this);
      deleteMaterial(this.lastArr.toString()).then(res => {
          loading.close();
        this.queryList();
      });
    },
    resetPlace() {
      const _cascader = this.$refs.cascaderAddr;
      if (_cascader) {
        _cascader.$refs.panel.checkedValue = [];
        _cascader.$refs.panel.activePath = [];
        _cascader.$refs.panel.syncActivePath();
      }
    },
    //重置
    clearList() {
      this.resetPlace();
      this.from = {
        goodName: null,
        orderNum: null,
        parentId: null
      };
    },
    //列表查询方法
    queryList() {
      const loading = this.$load(this);
      typelistMaterial({ goodType: "farm_machine" }).then(res => {
        loading.close();
        this.dataList = res.data.data;
        let parentObjs = [];
        this.tree2List(JSON.parse(JSON.stringify(this.dataList))).map(item => {
          if (item.children.length > 0) {
            parentObjs.push(item);
          }
        });
        this.childArr = [];
        parentObjs.forEach(i => {
          this.childArr.push(i.id * 1);
        });
      });
    },
    array2String(arr, separator) {
      let text = "";
      if (arr.length == 0) {
        return text;
      } else {
        arr.forEach(item => {
          text = text + item + separator;
        });
        return text.substr(0, text.length - 1);
      }
    },
    tree2List(node) {
      let stack = node,
        data = [];
      while (stack.length != 0) {
        let pop = stack.pop();
        data.push({
          id: pop.id,
          children: pop.children,
          goodName: pop.goodName,
          parentId: pop.parentId
        });
        let children = pop.children;
        if (children) {
          for (let i = children.length - 1; i >= 0; i--) {
            stack.push(children[i]);
          }
        }
      }
      return data;
    },

    danxuan() {
      this.handleNodeClick();
    },
    handleNodeClick() {
      //   let itemIds = this.$refs.treel.getCheckedKeys();
      let itemObjs = this.$refs.tree.getCheckedKeys();

      let resultArr = [];
      itemObjs.forEach(id => {
        if (this.childArr.indexOf(id * 1) == -1) {
          resultArr.push(id);
        }
      });
      this.lastArr = resultArr;
    },
    newSelet(obj) {
      this.from.parentId = obj[obj.length - 1];
    },
    delivery() {

        this.$refs.toolForm.validate((valid) => {
            if (valid) {
                this.from.goodType = "farm_machine";
                const loading = this.$load(this);
                this.from.unit = "空"
                newaddMaterial(this.from).then(res => {
                    loading.close();
                    if(res.data.code==200){
                        this.queryList();
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        });
                    }else{
                        this.$message({
                            type: 'error',
                            message: res.data.msg
                        });
                    }
                });
                this.addNews = false;
            } else {
                return false;
            }
        });
    },
    newList() {
      this.clearList();
      this.$nextTick(() => {
        const loading = this.$load(this);
        typelistMaterial({ goodType: "farm_machine" }).then(res => {
            loading.close();
            const rootObj = [{
                id:2,
                path: 1,
                parentId: 0,
                goodType: "farm_machine",
                goodName: "农具",
                children: res.data.data
            }]
          this.seleList = rootObj;
          this.addNews = true;
          // console.log(this.from.seleList)
        });
      });
    },
    sendInfo() {
        this.$refs.toolFormData.validate((valid) => {
            if (valid) {
                this.dialogVisible = false;
                this.targetNode.label = this.info;
                this.fromData.goodType = "farm_machine";
                this.fromData.id = this.wzId;
                this.fromData.parentId = this.wzParentId;
                const loading = this.$load(this);
                reviseMaterial(this.fromData).then(res => {
                    loading.close();
                    if(res.data.code==200){
                        this.$message({
                            type: 'success',
                            message: res.data.msg
                        });
                        this.queryList();
                    }else{
                        this.$message({
                            type: 'error',
                            message: res.data.msg
                        });
                    }
                });
            } else {
                return false;
            }
        });
    },
    append(data) {
      this.targetNode = data;
      this.info = data.label;
      this.dialogVisible = true;
      console.log(data);
      this.fromData.goodName = data.goodName;
      this.fromData.orderNum = data.orderNum;
      this.wzId = data.id;
      this.wzParentId = data.parentId;
    },
    remove() {
      this.delet = true;
      //   const parent = node.parent;
      //   const children = parent.data.children || parent.data;
      //   const index = children.findIndex(d => d.id === data.id);
      //   children.splice(index, 1);
    }
  },
  mounted() {
    PubSub.subscribe("nongjuguanli", (msg, data) => {
      console.log(data)
      if (data == 1) {
        this.queryList();
      } else {
      }
    });
  },
  beforeDestroy() {
    PubSub.unsubscribe("nongjuguanli");
  }
};
</script>

<style scoped>
.titFirst {
  width: 100%;
  height: 50px;
  line-height: 50px;
  /* background: pink; */
  font-weight: 700;
  font-size: 16px;
}
.titFirst i {
  color: green;
}
.btn_purpose {
  display: flex;
  /* text-align: right; */
  justify-content: flex-end;
  font-size: 16px;
  align-items: center;
}
.btn_purpose div {
  margin: 10px;
}
.btn_purpose_left {
  width: 80px;
  height: 30px;
  background: green;
  border-radius: 6px;
  line-height: 30px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  color: white;
}
.btn_purpose_right {
  width: 80px;
  height: 30px;
  background: red;
  border-radius: 6px;
  line-height: 30px;
  text-align: center;
  font-size: 14px;
  cursor: pointer;
  color: white;
}
.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.titFirst {
  display: inline-block;
  display: flex;
  justify-content: space-between;
}
.el-tree /deep/ .el-tree-node .el-tree-node__content {
  height: 43px;
  background: #e5f6f0;
  margin: 1px 0;
  color: #007d39;
}
.el-tree /deep/ .is-current > .el-tree-node__content {
  background: rgba(110, 184, 45, 1) !important;
  color: #fff !important;
}
.el-tree /deep/ .el-tree-node__label {
  display: inline-block;
  width: 72%;
}

.el-tree /deep/ .el-tree-node__children .el-tree-node__content {
  height: 34px;
  background: #e4e4e4 !important;
}
.el-tree /deep/ .el-tree-node__children .is-current .el-tree-node__content {
  background: #a5a5a5 !important;
  color: #fff !important;
}
.el-tree /deep/ .el-tree-node__children .el-tree-node__content {
  color: #007d39 !important;
}
.el-tree-node__expand-icon.is-leaf {
  color: transparent !important;
}
</style>
